<template>
  <div class="app-container">

    <!-- 添加或修改产品展示对话框 -->

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" :style="{width: '50%'}" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品列表图">
          <uploadImage v-model="form.listPic"/>
        </el-form-item>

        <el-form-item label="语言类型" prop="language">
          <el-select v-model="form.language" placeholder="请选择语言类型">
            <el-option
              v-for="dict in languageOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品分类  " prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择产品分类">
            <el-option
              v-for="type in typeList"
              :key="type.id"
              :label="type.typeName"
              :value="parseInt(type.id)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="详情图">
          <el-upload
            :action="uploadImgUrl"
            :http-request="uploadAvatar"
            :headers="headers"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
          <!-- <uploadImage v-model="form.img"/> -->
        </el-form-item>

        <el-form-item label="产品内容">
          <editor-bar v-model="form.content" >

          </editor-bar>

        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;margin-left:-100px;margin-top:10px;">
        <el-button type="primary" @click="submitForm">保  存</el-button>
        <el-button @click="close()">返回</el-button>
      </div>

  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, exportProduct } from "@/api/reveal/product";
import { listProductType } from "@/api/reveal/productType";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UploadImage from '@/components/UploadImage';
import 'mavon-editor/dist/css/index.css';
import request from '@/utils/request';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
import EditorBar   from "@/components/wangEditor";

export default {
  name: "ProductEdit",
  components: {
    UploadImage,
    EditorBar,
    Treeselect
  },
   data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 产品展示表格数据
      productList: [],
      // 产品类型树选项
      productTypeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 语言类型字典
      languageOptions: [],
      // 表单参数
      form: {
      },
      queryParams: {
      },
      // 表单校验
      rules: {
      },
      typeList:[],
      id:'',
      content:'', // 输入的markdown
      html:'',    // 及时转的html
      dialogImageUrl: '',
      dialogVisible: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API +  "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      picList: []
    };
  },
  created() {
    const id = this.$route.params && this.$route.params.id;
    this.id = id;
    if(id){
      this.handleUpdate(id);
    }else{
      this.reset();
    }
    //获取字典
    this.getDicts("language").then(response => {
      this.languageOptions = response.data;
    });
    //获取分类
    this.getTypeList();
  },
  methods: {

    uploadAvatar(item) {
      let formdata = new FormData();
      formdata.append('file', item.file);
      let uid = item.file.uid;
      request({
          url: "/common/upload",
          method: 'post',
          data: formdata
        }).then(res => {
          if (res.code === 200) {
            this.picList.push({ key: uid, url: res.url })
          } else {
               console.log("图片上传失败")
          }
      }).catch(err => {
          console.log(err)
      })
    },


    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isPng = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 10

        if (!isJPG && !isPng) {
          this.$message.error('上传图片只能是 JPG或png 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 10MB!')
        }
        return (isJPG || isPng) && isLt2M
      },
      handleRemove(file, fileList) {
        for (const i in this.picList) {
            if (this.picList[i].key === file.key) {
              this.picList.splice(i, 1)
            }
        }
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        console.log(file);
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.typeName,
        children: node.children
      };
    },
    	/** 查询部门下拉树结构 */
    getTypeList() {
      listProductType().then(response => {
        this.typeList=response.rows;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        listPic: null,
        productName: null,
        content: null,
        typeId: null,
        language: null,
        img: null
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset();
      getProduct(id).then(response => {
        this.form = response.data;
        //图片
        let img =  response.data.img;
        if(img){
          let imgs =[];
          imgs =img.split(',');
          imgs.forEach((item, index) => {
            let url = {key:index,url:item};
            this.fileList.push(url);
            this.picList.push(url);
          })
        }


      });
    },
    onClick (e, editor) {
      console.log('Element clicked')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log(this.content);
            console.log(this.html);
        if (valid) {
          if (this.form.id != null) {
            let img = "";
            console.log(this.picList);
            this.picList.forEach((item, index) => {
              if(index ===0){

                img += item.url;
              }else{
                img += ","+item.url;
              }

            });
            this.form.img = img;

            updateProduct(this.form).then(response => {
              this.msgSuccess("修改成功");
               this.$store.dispatch('tagsView/delView', this.$route);
               this.$router.go(-1);
            });
          } else {
            addProduct(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.$store.dispatch('tagsView/delView', this.$route);
              this.$router.go(-1);
            });
          }


        }
      });
    },
    close() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
    }

  }
};
</script>
